import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, message, Modal, Table, Row, Card } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { getReasonTable, removeReason, updateConfig } from './service.js';
import { ConsoleSqlOutlined } from '@ant-design/icons';
const { confirm } = Modal

const Tables = () => {
  const [createModalVisible, handleCreateModalVisible] = useState(false); // 新建弹框
  const [updateModalVisible, handleUpdateModalVisible] = useState(false); //  编辑
  const [updateData, saveUpdateData] = useState({}) // 编辑数据
  const [selectedRowKeys, handleSelectedRowKeys] = useState('') // 勾选
  const [selectedRows, handleSelectedRows] = useState([]) // 勾选
  const [dataSource, handleDataSource] = useState([]) // 列表数据
  const [height, controlH] = useState(document.body.clientHeight - 400);
  const columns = [
    {
      title: '行李箱尺寸',
      dataIndex: 'content',
    },
    {
      title: '创建人',
      dataIndex: 'createUser'
    },
    {
      title: '更新人',
      dataIndex: 'updateUser',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      // sorter: true,
      valueType: 'dateTime',
    },
  ];
  // 获取列表
  const getList = () => {
    getReasonTable({ type: '2' }).then(res => {
      res && res.map(item => {
        if (!item.updateTime) {
          item.updateTime = item.createTime
          item.updateUser = item.createUser
          return item
        }
      })
      handleDataSource(res)
    })
  }
  // 添加更新
  const handleSubmit = async (fields, text) => {
    const hide = message.loading(`正在${text}`);
    try {
      const res = await updateConfig({
        actConfigInfo: { ...fields, type: '2' },
      });
      if (res.code === '1') {
        hide()
        message.error(res.msg);
      } else {
        hide()
        message.success(`${text}成功`)
        return true;
      }
    } catch (error) {
      hide();
      message.error(`${text}失败请重试！`);
    }
  };
  // 删除
  const handleRemove = async (selectedRows) => {
    console.log(selectedRows)
    try {
      await removeReason({
        ids: selectedRows.map(row => row.id).toString(),
      });
      message.success('删除成功，即将刷新');
      getList()
      return true;
    } catch (error) {
      message.error('删除失败，请重试');
    }
  };
  useEffect(() => {
    getList()
  }, [])

  const tableSelectChange = (selectedRowKeys, selectedRows) => {
    handleSelectedRowKeys(selectedRowKeys)
    handleSelectedRows(selectedRows)
  }

  const rowSelection = {
    selectedRowKeys,
    onChange: tableSelectChange,
  };

  return (
    <Card>
      <Row style={{ marginBottom: 10, display: 'flex', justifyContent: 'flex-end' }}>
          <Button style={{ marginRight: 20 }} icon='plus' type="primary" onClick={() => {
            handleCreateModalVisible(true)
          }}>
            新建
        </Button>
        <Button style={{ marginRight: 20 }} icon='edit' onClick={() => {
          if (selectedRows.length === 0) {
            message.error('请选择编辑的条目')
          } else if (selectedRows.length > 1) {
            message.error('只能选择一条进行编辑')
          } else {
            handleUpdateModalVisible(true)
            saveUpdateData(selectedRows[0])
          }
        }}>
          编辑
        </Button>
        <Button icon='delete' onClick={() => {
          if (selectedRows.length === 0) {
            message.error("请选择删除的条目")
          } else {
            confirm({
              title: '提示',
              content: '确认操作后，该尺寸模块数据将被删除，无法使用，你还要继续吗？',
              cancelText: '取消',
              okText: '确认',
              onOk: async () => {
                await handleRemove(selectedRows);
                handleSelectedRows([])
                handleSelectedRowKeys('')
              }
            })
          }
        }}>删除</Button>
      </Row>
      <Table
        scroll={{ y: height }}
        rowKey='id'
        rowSelection={rowSelection}
        columns={columns}
        dataSource={dataSource}

      />
      {/* 新建 */}
      <CreateForm
        onSubmit={async value => {
          const success = await handleSubmit(value, '添加');
          if (success) {
            handleCreateModalVisible(false);
            getList()
            handleSelectedRowKeys('')
            handleSelectedRows([])
          }
        }}
        onCancel={() => handleCreateModalVisible(false)}
        createModalVisible={createModalVisible}
      />
      {/* 编辑 */}
      <UpdateForm
        onSubmit={async value => {
          const success = await handleSubmit(value, '编辑');
          if (success) {
            handleUpdateModalVisible(false);
            getList()
            handleSelectedRowKeys('')
            handleSelectedRows([])
          }
        }}
        onCancel={() => handleUpdateModalVisible(false)}
        updateModalVisible={updateModalVisible}
        updateData={updateData}
      />
    </Card>
  );
};

export default Form.create()(Tables);
